import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {View, Picker, Block, ScrollView, Button} from '@tarojs/components'
import './register.scss'
import {AtSteps, AtInput, AtForm, AtButton, AtIcon, AtModal, AtModalHeader, AtModalAction} from 'taro-ui'
import WxValidate from '../../../utils/wx-validate'
import {user} from '../../../utils/user.service'
import {http} from '../../../utils/http'
import {BECOME_CONTENT, REGION_ALL, REGISTER_SELLER, REGISTER_TOP_SELLER} from '../../../constants/api'
import {platform} from '../../../utils/platform-settting.service'
import {vcmonitor} from "../../../utils/tools";
import {h5Wx} from "../../../utils/h5.service";
import DistPicker from "../../components/distPicker";
import GzhAuth from "../../../components/gzh-auth/gzh-auth"
import {getContent} from "../../../utils/handlerPublicCode";

interface formData {
  sid?: number
  parent_seller_id?: number
  source_user_id?: number
  poster_name: string
  real_name: string
  phone: string
  slogan: string
  company: string
  area: string[]
  address: string
  delivery_province: string
  delivery_city: string
  delivery_area: string
}

export default class Register extends Component {
  state: {
    addressData: any
    items: { title: string; sucess: boolean }[]
    stepIndex: number
    formData: formData
    errList: {
      sid?: boolean
      parent_seller_id?: boolean
      source_user_id?: boolean
      poster_name?: boolean
      real_name: boolean
      phone: boolean
      slogan?: boolean
      company?: boolean
      area?: boolean
      address?: boolean
      delivery_province?: boolean
      delivery_city?: boolean
      delivery_area?: boolean
    }
    submiting: boolean
    showLoading: boolean
    registerurl: string
    viewShow: boolean
    showFloat: any
    minHeight: any
    becomeContent: any
    from: any
  } = {
    showFloat: false,
    minHeight: 0,
    becomeContent: false,
    addressData: [],
    items: [
      {title: '填写信息', sucess: false},
      {title: '提交申请', sucess: false},
      {title: '完成', sucess: false},
    ],
    stepIndex: 0,
    formData: {
      // sid: 0,
      // source_user_id: 0,
      poster_name: '',
      real_name: '',
      phone: '',
      slogan: '',
      company: '',
      area: [],
      address: '',
      delivery_province: '',
      delivery_city: '',
      delivery_area: '',
    },
    errList: {
      real_name: false,
      phone: false,
    },
    submiting: false,
    showLoading: true,
    registerurl: '',
    from: '',
    viewShow: false,
  }

  async UNSAFE_componentWillMount() {
    const {from = '', showDialog = ''} = Taro.getCurrentInstance().router.params
    const becomeContent = await http.carGet(BECOME_CONTENT, {})
    Taro.getSystemInfo({
      success: (res) => {
        this.setState({minHeight: res.windowHeight / 2 - 60})
      }
    })
    this.setState({becomeContent: becomeContent.content || '', showFloat: !!showDialog, from})
    if (from){
      this.setState({viewShow: true})
      return
    }
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
      const data = await http.carGet(REGION_ALL)
      this.setState({addressData: data})
    }
    setTimeout(() => {
      this.setState({viewShow: true})
    }, 500)
    const isLogin = await user.checkLogin()
    let platformSet = platform.info
    if (!platform.isLoaded) {
      platformSet = (await platform.getSetting()) || platform.info
    }
    if (platformSet) {
      const {sid = '', sourceUserId = '', timestamp = '', sellerId = ''} = Taro.getCurrentInstance().router.params
      if (platformSet.sellerRegType != 2 && platformSet.sellerRegType != 3) {
        let mpkey = ''
        const uInfo = Taro.getStorageSync('user') || ''
        if (uInfo && uInfo.mpkey && uInfo.mpkey !== 'undefined') {
          mpkey = uInfo.mpkey
        }
        Taro.redirectTo({
          url: `/common/distributor/invite/join?sid=${sid}&sourceUserId=${sourceUserId}&timestamp=${timestamp}&sellerId=${sellerId}&mpkey=${mpkey}`
        })
      } else {
        if (!isLogin) {
          Taro.showToast({
            title: '你还未登录，请登录',
            icon: 'none',
          })
          const timer = setTimeout(() => {
            clearTimeout(timer)
            user.jumpLogin()
          }, 1000)
          return
        }
      }
    } else {
      if (!isLogin) {
        Taro.showToast({
          title: '你还未登录，请登录',
          icon: 'none',
        })
        const timer = setTimeout(() => {
          clearTimeout(timer)
          user.jumpLogin()
        }, 1000)
        return
      }

    }
  }

  async componentDidShow() {
    vcmonitor(this)
    const {from = ''} = Taro.getCurrentInstance().router.params
    if (from){
      return
    }
    const isLogin = await user.checkLogin()
    this.setState({showLoading: !isLogin})
    let platformSet = platform.info
    if (!platform.isLoaded) {
      platformSet = (await platform.getSetting()) || platform.info
    }
    const bindSellerId = Taro.getStorageSync('bindSellerId') || 0;
    let {sellerId = '', sid = '', sourceUserId = '', self = '', mpkey = ''} = Taro.getCurrentInstance().router.params
    const formData = this.state.formData
    const registerurl = sellerId ? REGISTER_SELLER : REGISTER_TOP_SELLER
    if (sellerId) {
      if (platformSet.isSellerPermanentLock) {
        if (bindSellerId) {
          sellerId = bindSellerId
        }
      }
      if (self) {
        formData['parent_seller_id'] = bindSellerId || parseInt(sellerId)
      } else {
        formData['parent_seller_id'] = parseInt(sellerId)
      }

      Taro.setStorageSync('bindSellerId', formData['parent_seller_id'])
    }

    if (sid) {
      formData['sid'] = parseInt(sid)
      Taro.setStorageSync('sid', formData['sid'])
    } else {
      if (Taro.getStorageSync('sid')) {
        formData['sid'] = Taro.getStorageSync('sid')
      }
    }
    if (sourceUserId) {
      formData['source_user_id'] = parseInt(sourceUserId)
      Taro.setStorageSync('sourceUserId', formData['source_user_id'])
    } else {
      if (Taro.getStorageSync('sourceUserId')) {
        formData['source_user_id'] = Taro.getStorageSync('sourceUserId')
      }
    }
    this.setState({formData, registerurl})
    if (process.env.TARO_ENV === 'h5') {
      await user.mpKeyCheckLogin(mpkey, 0, '')
    }
  }

  stepChange(index) {
  }

  inputChange(type, value) {
    const oldData = this.state.formData
    oldData[type] = value
    this.setState({formData: oldData})
  }

  regionChange(e) {
    const area = e.detail.value
    const oldData = this.state.formData
    oldData['area'] = area
    oldData['delivery_area'] = area[2]
    oldData['delivery_city'] = area[1]
    oldData['delivery_province'] = area[0]
    this.setState({formData: oldData})
  }

  rules = {
    real_name: {
      required: true,
      minlength: 2
    },
    phone: {
      required: true,
      digits: true,
      minlength: 11,
      maxlength: 11
    },
    poster_name: {
      required: true
    },
    slogan: {
      required: true
    }
  }
  message = {
    real_name: {
      required: "姓名不能为空",
    },
    phone: {
      required: "请填写手机号",
      digits: "手机号码不正确",
      minlength: "手机号码不正确",
      maxlength: "手机号码不正确"
    },
    poster_name: {
      required: '请填写昵称'
    },
    slogan: {
      required: '请填写广告语'
    }
  }

  submit() {
    this.setState({submiting: true}, async () => {
      const validate = new WxValidate(this.rules, this.message)
      if (!validate.checkForm(this.state.formData)) {
        const oldData = this.state.errList
        if (validate && validate.errorList && validate.errorList[0].param) {
          oldData[validate.errorList[0].param] = true
          Taro.showToast({
            title: validate.errorList[0].msg,
            icon: 'none'
          })
        }
        this.setState({errList: oldData, submiting: false})
        return false;
      }
      const ret = await http.post(this.state.registerurl, {...this.state.formData})
      if (ret) {
        await user.setUserData()
        this.setState({submiting: false})
        if (this.state.becomeContent){
          this.setState({showFloat: true})
        } else {
          Taro.showModal({
            title: '提示',
            content: '保存成功，是否去完善资料？',
            success(res) {
              if (res.confirm) {
                Taro.redirectTo({url: '/distributor/profile/profile'})
              } else if (res.cancel) {
                Taro.switchTab({url: '/pages/my/index/index'})
              }
            }
          })
        }
      } else {
        this.setState({submiting: false})
      }

    })
  }

  H5Change(data) {
    const area = data.address.split(',')
    const oldData = this.state.formData
    oldData['area'] = area
    oldData['areaIndex'] = data.addary
    oldData['delivery_area'] = area[2]
    oldData['delivery_city'] = area[1]
    oldData['delivery_province'] = area[0]
    this.setState({formData: oldData})
  }

  render() {
    const {from, showFloat, minHeight, becomeContent, viewShow, items, stepIndex, formData, submiting, errList, showLoading, addressData} = this.state
    return (
      <View className='register-root'>
        <GzhAuth />
        {viewShow && <Block>
          <View className='steps'>
            <AtSteps items={items} onChange={this.stepChange.bind(this)} current={stepIndex} />
          </View>
          <View className='title'>{process.env.fxName}信息：</View>
          <AtForm>
            <AtInput error={errList.poster_name} type='text' value={formData.poster_name} name='poster_name'
              maxLength={12} onChange={this.inputChange.bind(this, 'poster_name')} title='昵称'
              placeholder='请填写昵称（2-12个字）'
            />
            <AtInput error={errList.real_name} type='text' value={formData.real_name} name='real_name' maxLength={15}
              onChange={this.inputChange.bind(this, 'real_name')} title='姓名'
              placeholder='请填写真实姓名，将在结算时使用'
            />
            <AtInput error={errList.phone} type='text' value={formData.phone} name='phone'
              onChange={this.inputChange.bind(this, 'phone')} title='手机号' placeholder='请填写手机号（无需+86）'
            />
            <AtInput error={errList.slogan} type='text' value={formData.slogan} name='slogan'
              onChange={this.inputChange.bind(this, 'slogan')} title='广告语' placeholder='请写广告语'
            />
            <AtInput error={errList.company} type='text' value={formData.company} name='company'
              onChange={this.inputChange.bind(this, 'company')} title='公司名称' placeholder='请填写公司名称'
            />
            {process.env.TARO_ENV === "h5" ?
              <View className='h5add'><DistPicker address={formData.area.join(',')} addressData={addressData}
                onChange={this.H5Change.bind(this)}
              /></View>
              :
              <Picker mode='region' value={formData.area} onChange={this.regionChange.bind(this)}>
                <View className='at-input'>
                  <View className='at-input__container'>
                    <View className='at-input__title'>选择城市</View>
                    <View className='at-input__input'>{formData.area.join(" ")}</View>
                  </View>
                </View>
              </Picker>
            }
            <AtInput error={errList.address} type='text' value={formData.address} name='address'
              onChange={this.inputChange.bind(this, 'address')} title='详细地址' placeholder='请填写详细地址'
            />
          </AtForm>
          {!from && <View className='btn-box'><AtButton type='primary' loading={submiting} disabled={submiting}
            onClick={this.submit.bind(this)}
          >提交申请</AtButton></View>}
        </Block>}
        {showFloat && <AtModal className='model' isOpened={showFloat} onClose={() => {
          this.setState({showFloat: false})
        }}
        >
          <AtModalHeader><AtIcon onClick={() => {
            this.setState({showFloat: false})
          }} className='close-cla' value='close' size='20' color='#888888'
          /></AtModalHeader>
          <View className='w-b-ba'>
            <ScrollView
              style={`min-height:${minHeight + 'px'};max-height:${minHeight + 'px'}`}
              className='scrollView'
              scrollY
            >
              {process.env.TARO_ENV === "weapp" && <parser selectable html={becomeContent || ''} />}
              {process.env.TARO_ENV === "tt" && <rich-text preview selectable nodes={getContent(becomeContent)} />}
              {process.env.TARO_ENV === "h5" && !!becomeContent &&
              <View dangerouslySetInnerHTML={{__html: becomeContent}} />}
            </ScrollView>
          </View>
          <AtModalAction>
            <Button onClick={() => {this.setState({showFloat: false})}} className='readed'>确定</Button>
            {!from && <View onClick={()=> { Taro.redirectTo({url: '/distributor/profile/profile'}) }} className='complete-material'>去完善资料</View>}
          </AtModalAction>
        </AtModal>}
      </View>
    )
  }
}
